package org.deng.learn.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDateTime;

/**
 * @author 邓力宾
 * @date 2021/1/6 9:02
 * @desc 测试插入日期
 */
public class TestDate {


    private final static String JDBC_URL = "jdbc:mysql://192.168.2.177:3306/denglibin?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
    //private final static String JDBC_URL = "jdbc:mysql://192.168.2.177:3306/denglibin?useSSL=false&useUnicode=true&characterEncoding=utf-8";
    private final static String USERNAME = "root";
    private final static String PASSWORD = "denglibin";
    TestDate() throws ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver"); //注册驱动
    }

    /**
     * 获取连接
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(JDBC_URL,USERNAME, PASSWORD);
    }

    /**
     * 事务操作
     */
    public void commitTransaction(){
        Connection connection = null;
        PreparedStatement statement1 = null;

        try{
            connection = getConnection();
            connection.setAutoCommit(false);
            statement1 = connection.prepareStatement("UPDATE user set update_date=? where id=1 ");

            statement1.setObject(1, LocalDateTime.now());
            statement1.executeUpdate();

            connection.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                System.out.println("回滚事务。。。。。。。。。。。。。。。。。");
                if(connection != null){
                    connection.rollback();
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {
            try {
                if(statement1 != null){
                    statement1.close();
                }

                if(connection != null){
                    connection.close();
                }
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }

    public  static  void  main(String[] args) throws ClassNotFoundException {
        TestDate TestDate = new TestDate();
        TestDate.commitTransaction();
    }
}
